<template>
  <PageContainer title="后台公告">
    <div class="notice-list-container">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索公告标题"
          clearable
          style="width: 300px"
          @clear="handleSearch"
          @keyup.enter="handleSearch"
          prefix-icon="el-icon-search"
        />
      </div>

      <!-- 公告列表表格 -->
      <div class="table-section" style="margin-top: 20px">
        <el-table
          :data="noticeList"
          :loading="loading"
          border
          stripe
          style="width: 100%"
          @row-click="handleRowClick"
          :row-class-name="(scope) => scope.row ? 'table-row-hover' : ''"
        >
          <el-table-column
            prop="title"
            label="公告标题"
            align="left"
            min-width="250"
          >
            <template #default="scope">
              <span class="title-text" :title="scope.row.title">
                {{ scope.row.title }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="tag"
            label="公告标签"
            align="center"
            width="140"
          >
            <template #default="scope">
              <el-tag :type="getTagType(scope.row.tag)">
                {{ scope.row.tag || '无标签' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="publishTime"
            label="发布时间"
            align="center"
            width="180"
            sortable
            :sort-method="(a, b) => new Date(b.publishTime) - new Date(a.publishTime)"
          >
            <template #default="scope">
              {{ formatTime(scope.row.publishTime) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="creatorName"
            label="创建人"
            align="center"
            width="120"
          >
            <template #default="scope">
              {{ scope.row.creatorName || '未知管理员' }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="120"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleViewDetail(scope.row, $event)"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
        <el-empty
          v-if="!loading && noticeList.length === 0"
          description="暂无管理后台相关公告"
          style="margin: 80px 0"
        >
          <template #image>
            <img
              src="@/assets/super.jpg"
              alt="无公告"
              style="width: 180px; height: 180px"
            />
          </template>
        </el-empty>
      </div>

      <!-- 分页组件 -->
      <div class="pagination-section" style="margin-top: 16px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
        />
      </div>
    </div>
  </PageContainer>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElTag } from 'element-plus';
import { useRouter } from 'vue-router';
import dayjs from 'dayjs';
import PageContainer from '@/components/PageContainer.vue';
import { getNoticeList } from '@/api/admin';

const router = useRouter();

// 调试：打印组件初始化信息
console.log('=== 公告列表组件初始化 ===');

// 搜索参数
const searchKeyword = ref('');
console.log('初始搜索关键词:', searchKeyword.value);

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);
console.log('初始分页参数:', { currentPage: currentPage.value, pageSize: pageSize.value });

// 列表数据与状态
const noticeList = ref([]);
const loading = ref(false);

/**
 * 加载管理后台公告列表（含详细调试日志）
 */
const loadAdminNoticeList = async () => {
  try {
    loading.value = true;
    console.log('=== 开始请求公告列表 ===');
    console.log('请求参数:', {
      page: currentPage.value,
      limit: pageSize.value,
      object: '管理后台',
      keyword: searchKeyword.value.trim()
    });

    // 调用接口后，result 是 Axios 响应对象，需从 result.data 中取业务数据
    const result = await getNoticeList({
      page: currentPage.value,
      limit: pageSize.value,
      object: '管理后台',
      keyword: searchKeyword.value.trim()
    });

    console.log('接口响应（完整Axios对象）:', result);
    const businessData = result.data; // 后端返回的业务数据在 data 里
    console.log('业务数据:', businessData);

    if (businessData.code === '0000') {
      noticeList.value = businessData.data.list || [];
      totalCount.value = businessData.data.pagination?.total || 0;
      console.log('公告列表数据:', noticeList.value);
      console.log('总条数:', totalCount.value);
    } else {
      ElMessage.error(businessData.message || '获取管理后台公告失败');
      console.error('接口业务错误:', businessData.message || '未知错误');
    }
  } catch (error) {
    ElMessage.error('网络异常，请重试');
    console.error('请求公告列表异常:', error);
    console.error('异常详情:', error.message, error.response?.data);
  } finally {
    loading.value = false;
    console.log('=== 请求公告列表结束 ===');
  }
};

// 搜索事件
const handleSearch = () => {
  console.log('搜索关键词变化:', searchKeyword.value);
  currentPage.value = 1;
  loadAdminNoticeList();
};

// 分页事件：每页条数变化
const handleSizeChange = (val) => {
  console.log('每页条数变化:', val);
  pageSize.value = val;
  currentPage.value = 1;
  loadAdminNoticeList();
};

// 分页事件：页码变化
const handleCurrentChange = (val) => {
  console.log('页码变化:', val);
  currentPage.value = val;
  loadAdminNoticeList();
};

// 标签类型映射
const getTagType = (tag) => {
  const tagTypeMap = {
    '系统通知': 'success',
    '紧急通知': 'danger',
    '活动提醒': 'primary',
    '其他': 'info'
  };
  return tagTypeMap[tag] || 'default';
};

// 时间格式化
const formatTime = (time) => {
  return time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '未记录';
};

// 行点击
const handleRowClick = (row) => {
  console.log('点击公告行，ID:', row.id);
  router.push(`/system/notice-detail/${row.id}`);
};

// 查看详情按钮
const handleViewDetail = (row, event) => {
  event.stopPropagation();
  console.log('点击查看详情按钮，ID:', row.id);
  router.push(`/system/notice-detail/${row.id}`);
};

// 页面挂载时加载列表
onMounted(() => {
  console.log('组件挂载，开始加载公告列表');
  loadAdminNoticeList();
});
</script>

<style lang="scss" scoped>
.notice-list-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.search-section {
  padding: 8px 0;
  border-bottom: 1px solid #f2f2f2;
}

::v-deep .table-row-hover {
  &:hover > td {
    background-color: #f8f9fa !important;
    cursor: pointer;
  }
}

.title-text {
  display: inline-block;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #303133;
  &:hover {
    color: #409eff;
  }
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px 0;
}

@media (max-width: 768px) {
  .search-section .el-input {
    width: 100% !important;
  }
  ::v-deep .el-table__fixed-right {
    right: 0 !important;
  }
}
</style>